package com.lagshixiaobai.config;
import lombok.*;
import org.slf4j.MDC;

import java.io.Serializable;
import java.time.Instant;

@ToString(callSuper = true)
@EqualsAndHashCode
@Getter
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Result<T> implements Serializable {
    private static final int SUCCESS_CODE = ResultCode.SUCCESS.getCode();
    private static final int DEFAULT_ERR_CODE = ResultCode.UNKNOWN_ERROR.getCode();
    private static final String DEFAULT_ERR_MSG = ResultCode.UNKNOWN_ERROR.getMessage();

    /**
     * ===========================
     */
    private int code = SUCCESS_CODE;
    private String message = null;
    private T data = null;
    private long timestamp = Instant.now().toEpochMilli();
    private String traceId;

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.traceId = MDC.get("TRACE_ID");
    }

    //****************静态方法们********************
    public static <T> Result<T> ok() {
        return new Result<>();
    }

    public static <T> Result<T> ok(T data) {
        Result<T> result = ok();
        result.setData(data);
        return result;
    }

    public static <T> Result<T> fail() {
        Result<T> result = new Result<>();
        result.setErrCode(DEFAULT_ERR_CODE);
        result.setErrMsg(DEFAULT_ERR_MSG);
        return result;
    }

    public static <T> Result<T> fail(int errCode, String errMsg) {
        Result<T> result = fail();
        result.setErrCode(errCode);
        result.setErrMsg(errMsg);
        return result;
    }

    public static <T> Result<T> fail(int errCode, String errMsg, T data) {
        Result<T> result = fail();
        result.setErrCode(errCode);
        result.setErrMsg(errMsg);
        result.setData(data);
        return result;
    }

    /***************实例方法******************/

    /**
     * 判断是否成功
     * @return true or false
     */
    public boolean isSuccess() {
        return getCode() == SUCCESS_CODE;
    }

    /**
     * 设置负载数据
     *
     * @param data 返回数据
     * @return this本身
     */
    public Result<T> setData(T data) {
        this.data = data;
        return this;
    }

    /**
     * 设置错误码
     *
     * @param errCode 错误码
     */
    public void setErrCode(int errCode) {
        if (errCode == SUCCESS_CODE) {
            throw new RuntimeException("Your code is " + errCode + ".Which only means SUCCESS");
        }
        this.code = errCode;
    }

    // ==============快捷方式===================

    /**
     * 设置错误消息
     *
     * @param errMsg 错误消息
     */
    public void setErrMsg(String errMsg) {
        this.message = errMsg;
    }
}
